package com.iss.ljx.mybatis.flexigrid;

import com.iss.ljx.mybatis.anno.Columns;

import java.lang.reflect.Field;

/**
 * description TODO
 *
 * @author 流星
 * @date 2022/5/11 17:30
 */
public class PagingBean {
    /**
     * 当前页面
     */
    private Integer page = null;

    /**
     * 容量
     */
    private Integer rp = null;

    /**
     * 数据的开始
     */
    private Integer start = null;

    /**
     * 排序  asc
     */
    private String sortorder = null;

    /**
     * 按某个字段来排序
     */
    private String sortname = null;


    public String getSortname() {
        return sortname;
    }

    public void setSortname(String sortname) {
        this.sortname = sortname;
    }

    public Integer getPage() {

        return page;
    }

    public void setPage(Integer page) {

        this.page = page;

        dealStartRow();
    }

    /**
     * 计算出数据输出开始的行数
     */
    private void dealStartRow() {
        if ((this.page != null) && (this.rp != null)) {
            this.start = (Integer.valueOf(page) - 1) * Integer.valueOf(rp);
        }
    }

    public Integer getRp() {
        return rp;
    }

    public void setRp(Integer rp) {
        this.rp = rp;
        dealStartRow();

    }

    public String getSortorder() {
        return sortorder;
    }

    public void setSortorder(String sortorder) {
        this.sortorder = sortorder;
    }

    public Integer getStart() {
        return start;
    }

    public void setStart(Integer start) {
        this.start = start;
    }

    @Override
    public String toString() {
        return "PagingBean [page=" + page + ", rp=" + rp + ", start=" + start + ", sortorder=" + sortorder
                + ", sortname=" + sortname + "]";
    }

    /**
     * 基于反射，根据需要排序的成员变量名，利用@Columns注解，得到对应的数据库表的字段名
     *
     * @param <T>
     * @param class1
     */
    public <T> void deal(Class<T> class1) {
        if (sortname != null || "undefined".equals(sortname)) {
            Field[] fields = class1.getDeclaredFields();
            for (Field field : fields) {
                if (field.getName().equals(sortname)) {
                    if (field.isAnnotationPresent(Columns.class)) {
                        Columns columns = field.getAnnotation(Columns.class);
                        sortname = columns.value();
                    }
                    break;
                }
            }
        }
    }
}
